package com.banshuibao.bsb_android.http;

import android.text.TextUtils;

import com.banshuibao.bsb_android.MyApplication;
import com.zx.uploadlibrary.helper.ProgressHelper;
import com.zx.uploadlibrary.listener.ProgressListener;
import com.zx.uploadlibrary.listener.impl.UIProgressListener;

import java.io.File;
import java.io.IOException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by zyh on 2017/4/17.
 */

class OkHttpUpload implements ObservableOnSubscribe<String> {

    private String url;

    private UIProgressListener progressListener;

    private ArrayList<String> paths;

    OkHttpUpload(String url,String path, UIProgressListener progressListener) {
        this.url = url;
        this.progressListener = progressListener;
        paths = new ArrayList<>();
        paths.add(path);
    }

    @Override
    public void subscribe(final ObservableEmitter<String> e) throws Exception {
        Call call = OkHttpClientUtil.getInstance().getClient().newCall(getRequest(url, paths, progressListener));
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e1) {
                e.onError(new Throwable("上传失败"));
                e.onComplete();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() == 200)
                    e.onNext(response.body().string());
                else
                    e.onError(new Throwable("上传失败"));
                e.onComplete();
            }
        });
    }

    private String getCookieID() {
        String cookieId = MyApplication.applicationInstance.getCookieId();
        return TextUtils.isEmpty(cookieId) ? "" : cookieId;
    }


    private Request getRequest(String url, List<String> fileNames, ProgressListener uiProgressRequestListener) {
        okhttp3.Request.Builder builder = new okhttp3.Request.Builder();
        builder.header("cookieId", getCookieID());
        builder.url(url).post(ProgressHelper.addProgressRequestListener(getRequestBody(fileNames), uiProgressRequestListener));
        return builder.build();
    }

    private RequestBody getRequestBody(List<String> fileNames) {
        okhttp3.MultipartBody.Builder builder = new okhttp3.MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (int i = 0; i < fileNames.size(); ++i) {
            File file = new File(fileNames.get(i));
            String fileType = getMimeType(file.getName());
            builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse(fileType), file));
        }
        return builder.build();
    }

    private String getMimeType(String filename) {
        FileNameMap filenameMap = URLConnection.getFileNameMap();
        String contentType = filenameMap.getContentTypeFor(filename);
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        return contentType;
    }
}
